﻿using SBlogCore.Entitys.SystemManager;
using SBlogCore.WebAdminApplication.SysManager.IServices;
using SBlogCore.Common.DatabaseAccessor.Repositorys.Dapper;
using SBlogCore.WebAdminApplication.SysManager.Dto;

namespace SBlogCore.WebAdminApplication.SysManager.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class SysMenuManagerService : ISysMenuManagerService
    {
        public IDapperRepository _IDapperRepository;
        private readonly IRepository<SysMenu> _sysMenuRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperRepository"></param>
        /// <param name="sysMenuRepository"></param>
        public SysMenuManagerService(IDapperRepository dapperRepository, IRepository<SysMenu> sysMenuRepository)
        {
            _IDapperRepository = dapperRepository;
            _sysMenuRepository = sysMenuRepository;
        }


        /// <summary>
        /// 表结构查询方法
        /// </summary>
        /// <returns></returns>
        public async Task<List<TableDicModel>> List()
        {
            string sql = @"
                        SELECT
		                ROW_NUMBER() OVER(ORDER BY(SELECT 0)) AS 'Sort',
		                t.name AS 'TableName',
		                IC.COLUMN_NAME as 'ColumnName',
		                IC.DATA_TYPE as 'DataType',
		                IC.CHARACTER_MAXIMUM_LENGTH AS 'Length',
		                IC.IS_NULLABLE AS 'NullAble',
		                OBJECT_DEFINITION(SC.DEFAULT_OBJECT_ID) AS 'DefaultValue',
		                CONVERT(VARCHAR(100), SEP.VALUE) AS 'DescripTion'
                        FROM
	                    SYS.TABLES AS T
	                    INNER JOIN SYS.COLUMNS SC ON SC.OBJECT_ID = T.OBJECT_ID
	                    INNER JOIN INFORMATION_SCHEMA.COLUMNS IC ON IC.TABLE_NAME = T.NAME
	                    AND SC.NAME = IC.COLUMN_NAME
	                    LEFT JOIN SYS.EXTENDED_PROPERTIES SEP ON T.OBJECT_ID = SEP.MAJOR_ID
	                    AND SC.COLUMN_ID = SEP.MINOR_ID
	                    AND SEP.NAME = 'MS_DESCRIPTION'
                        WHERE 1 = 1
	                    --AND T.NAME = 'AIR_YB_XX'-- - 要查询的表名 * *
	                     AND SCHEMA_NAME(T.SCHEMA_ID) = 'dbo'
                        ORDER BY
	                    t.name,IC.ORDINAL_POSITION";
            var res = await _IDapperRepository.SelectAsync<TableDicModel>(sql);
            return res;
        }

        /// <summary>
        /// 添加菜单方法
        /// </summary>
        /// <param name="inPut"></param>
        /// <returns></returns>
        public async Task AddMenu(SysMenuInPut inPut)
        {
            bool haveMenu = await _sysMenuRepository.AnyAsync(s =>s.Component != null && (s.Name==inPut.Name|| (s.Component == inPut.Component && !s.Component.Contains("#"))));
            if (haveMenu)
                throw SBlogCoreException.Say($"此菜单已存在！");
            SysMenu sysMenu = inPut.Adapt<SysMenu>();
            //判断上级是否存在
            if (inPut.ParentInfoId.HasValue && inPut.ParentInfoId != 0)
            {
                var parentInfo = await _sysMenuRepository.FirstOrDefaultAsync(x => x.Id == inPut.ParentInfoId);
                if (parentInfo==null)
                    throw SBlogCoreException.Say($"此菜单所选父级菜单不存在！");
                sysMenu.Level = parentInfo.Level + 1;
                parentInfo.IsParent = true;
                await _sysMenuRepository.UpdateAsync(parentInfo);
            }
            await _sysMenuRepository.InsertAsync(sysMenu);
        }
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="inPut"></param>
        /// <returns></returns>
        public async Task UpdateMenu(SysMenuEditInPut inPut)
        {
            SysMenu menuInfo = await _sysMenuRepository.FirstOrDefaultAsync(w => w.Id == inPut.Id);
            if (menuInfo == null)
                throw SBlogCoreException.Say($"当前菜单不存在！");
            menuInfo.Path = inPut.Path;
            menuInfo.Name = inPut.Name;
            menuInfo.Redirect = inPut.Redirect;
            menuInfo.Component = inPut.Component;
            menuInfo.Order = inPut.Order;
            menuInfo.Hidden = inPut.Hidden;
            menuInfo.ParentInfoId = inPut.ParentInfoId;
            menuInfo.AlwaysShow = inPut.Meta.AlwaysShow;
            //menuInfo.NoCache = inPut.Meta.NoCache;
            //menuInfo.Breadcrumb = inPut.Meta.Breadcrumb;
            //menuInfo.Affix = inPut.Meta.Affix;
            //menuInfo.NoTagsView = inPut.Meta.NoTagsView;
            //menuInfo.ActiveMenu = inPut.Meta.ActiveMenu;
            //menuInfo.FollowAuth = inPut.Meta.FollowAuth;
            //menuInfo.CanTo = inPut.Meta.CanTo;
            menuInfo.Title = inPut.Meta.Title;
            menuInfo.Icon = inPut.Meta.Icon;
            if (inPut.ParentInfoId.HasValue && inPut.ParentInfoId != 0)
            {
                var parentInfo = await _sysMenuRepository.FirstOrDefaultAsync(x => x.Id == inPut.ParentInfoId);
                if (parentInfo == null)
                    throw SBlogCoreException.Say($"此菜单所选父级菜单不存在！");
                menuInfo.Level = parentInfo.Level + 1;
                parentInfo.IsParent = true;
                await _sysMenuRepository.UpdateAsync(parentInfo);
            }
            await _sysMenuRepository.UpdateAsync(menuInfo);
        }

        public async Task<List<SysMenuOptions>> GetMenuOptions()
        {
            List<SysMenu> list = await GetMenuDataList();
            var res = list.Adapt<List<SysMenuOptions>>();
            return res;
        }
        /// <summary>
        /// 查询菜单列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SysMenuOutPut>> GetMenuList()
        {
            List<SysMenu> res = await GetMenuDataList();
            if (res.Count == 0)
                throw SBlogCoreException.Say($"当前菜单不存在！");
            var data = res.Adapt<List<SysMenuOutPut>>();
            return data;
        }
        /// <summary>
        /// 获取无条件的数据
        /// </summary>
        /// <returns></returns>
        public async  Task<List<SysMenu>> GetMenuDataList()
        {
            var res =await  _sysMenuRepository.Where(x => true)
                .OrderBy(a => a.Order)
                .ToListAsync();
            return res.Where(w=>w.ParentInfoId==null).ToList();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task Delete(params long[]  idList)
        {
            var list = _sysMenuRepository.Where(w => idList.Contains(w.Id));
            if (!list.Any())
            {
                throw SBlogCoreException.Say($"要删除的数据不存在！");
            }
            await  _sysMenuRepository.DeleteRangeNowAsync(list.ToArray());
        }
    }
}
